package com.hxzy.tms.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.hxzy.tms.SessionHolder;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthorizationInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -6391719486772661560L;

    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        if (SessionHolder.get() == null) {
            String requestUrl = URLEncoder.encode(request.getRequestURL().toString() + "?"+request.getQueryString(), "utf-8");
            if ("XMLHttpRequest".equals(ServletActionContext.getRequest().getHeader("x-requested-with"))) {
                ServletActionContext.getResponse().getWriter()
                        .println("{\"status\":-1, \"message\":\"access denied.\", \"url\":\""+requestUrl+"\"}");
                return null;
            }
            response.sendRedirect(String.format("%s%s?redirectUrl=%s", request.getContextPath(), "/login-index.action", requestUrl));
            return null;
//            return Action.LOGIN;
        }
        return invocation.invoke(); 
    }

}
